/*
 * JaCoLiB
 * Copyright (C) 2008 Alessandro Serra
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package it.gashale.jacolib.rpc;

import it.gashale.jacolib.core.JacolibError;
import it.gashale.jacolib.core.ProtocolError;

import java.util.HashMap;
import java.util.Map;

public class RPCServer {
	protected Map<String,RPCMethodHandler> handlers;
	private RPCChannel channel;
	
	protected RPCServer() {
		handlers=new HashMap<String,RPCMethodHandler>();
	}
	public RPCChannel getRPCChannel() {
		return channel;
	}
	public void setRPCChannel(RPCChannel v) {
		channel=v;
	}
	
	public void register(String method, RPCMethodHandler h) {
		handlers.put(method,h);
	}
	public RPCResponse call(RPCRequest req) throws JacolibError {
		RPCMethodHandler handler=handlers.get(req.method);
		if(handler!=null) {
			return handler.handles(req);
		} else { 
			throw new ProtocolError("Unknow method.");
		}
	}
	/*
	 * quit
	 */
	public void quit() throws JacolibError {
		channel.quit();
	}
	protected void quit_p() {
		channel=null;
		handlers=null;
	}
}
